/**
 * Created by python on 18-11-9.
 */
var app = new Vue({
    el:"#app",
    data:{
        // 页面中需要使用到的数据，键值对
        activity:'',
        last_time:0,
        deadline_ms:0,
        now_ms:0,
        now: 0, // 当前毫秒数
        start: 0, // 开始报名毫米数
        end: 0, // 报名结束毫秒数

    },
    computed:{
        // 需要通过计算得到的数据，键值对 ，键是名称，值是匿名函数
    },
    mounted:function () {
        // 一加载就需要做的，直接是代码
        // 获取页面id
        id = get_query_string("id", 1)
        axios.get(host+"/activities/" + id)
            .then(response=>{
                this.activity=response.data;
                let now=response.headers.date;
                now = new Date(now);
                this.now= now.getTime();
                this.start = new Date(response.data.sign_up_start).getTime();
                this.end = new Date(response.data.sign_up_end).getTime();
                this.action = new Date(response.data.published_time).getTime();
                this.over = new Date(response.data.published_time).getTime();
                this.countdown(new Date(response.data.sign_up_end).getTime(), now.getTime())


            })
            .catch(erro =>{
                alert("出错了")
            })
    },
    methods:{
        // 需要用到的函数，键值对 ，键是名称，值是匿名函数
        // 倒计时
        countdown :function(deadline_ms, now_ms){
            this.now_ms = now_ms;
            this.deadline_ms = deadline_ms;
            if(now_ms<deadline_ms){
                setInterval(()=>{
                this.now_ms += 1000;
                this.last_time = this.deadline_ms - this.now_ms
                },1000)
            } else {
                //
            }

        },
        // 点击报名
        on_apply: function(activity_id){
            if(this.user_id && this.token){
                axios.post(host+"/activity",{
                activity_id: activity_id
                },{
                    // 向后端传递JWT token的方法
                    headers: {
                        'Authorization': 'JWT ' + this.token
                    },
                    responseType: 'json',
                })
                .then(response=>{
                    alert('报名成功')
                    location.reload()
                })
                .catch(erro =>{

                    alert(erro.data)
                })
            }else{
                location.href = './login.html';
            }

        }
    },
    filters:{
        ms2time: function (time_ms) {
            var day = Math.floor(time_ms/1000/60/60/24)
            var hours = Math.floor(time_ms/1000/60/60%24)
            var minutes = Math.floor(time_ms/1000/60%60)
            var seconds = Math.floor(time_ms/1000%60)
            return day + '天'+ hours + '时' +minutes+ '分' +seconds+ '秒'
        }
    }
})